<script setup lang="ts">
import { ref, onMounted } from 'vue'
// 获取支付确认信息api
import { getConsultOrderPre, createConsultOrder } from '@/api/consult'
// 获取挂号患者信息api
import { getPatientDetail } from '@/api/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showFailToast } from 'vant'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()
const payInfo = ref({} as ConsultOrderPreData)
// 1. 支付确认信息
const getPre = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type, // 问诊类型: 1找医生2极速问诊3开药问诊
    illnessType: store.consult.illnessType // 极速问诊级别：0普通1三甲
  })
  console.log('支付确认信息：', res)
  payInfo.value = res
}
// 2. 挂号患者信息
const patient = ref({} as Patient)
const getPatient = async () => {
  // console.log('患者ID：', store.consult.patientId)
  const res = await getPatientDetail(store.consult.patientId!)
  console.log('挂号患者信息：', res)
  patient.value = res
}

onMounted(() => {
  getPre()
  getPatient()
})

// 3. 创建订单并打开支付方式选择的弹层
// 是否同意支付协议
const agree = ref(false)
// 控制支付弹层显示
const show = ref(false)

// 订单ID
const orderId = ref('')
const createOrder = async () => {
  // 1. 判断是否同意支付协议
  if (!agree.value) return showFailToast('请同意支付协议！')

  // 2. 打开支付弹层
  show.value = true

  // 3. 创建挂号订单
  const res = await createConsultOrder(store.consult)
  // 存储订单ID
  orderId.value = res.id
  // 说明：一旦创建订单成功，之前存到pinia的数据需要删除（只能使用一次）
  // 场景：电商买东西（在购物车中），下单之后，购物车中的商品会被删除
  // store.clear() // 暂时先不删，方便测试支付
}

// 1. 阻止页面的回退
onBeforeRouteLeave(() => {
  // 如果订单已创建阻止回退
  if (orderId.value) return false
})
// 2. 阻止支付弹层关闭 =》用户确认
const router = useRouter()
const onClose = async () => {
  try {
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭', // 取消支付
      confirmButtonText: '继续支付', // 确认支付
      confirmButtonColor: 'var(--cp-primary)' // 控制确认按钮文字颜色
    })
    // 点了=》继续支付
    return false
  } catch (error) {
    // 点了=》仍要关闭
    // 1. 清空订单ID
    orderId.value = ''
    // 2. 跳转订单列表
    router.push('/user/consult')
    return true
  }
}
// 4. 支付挂号订单
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="createOrder"
    />

    <!-- 支付弹层 -->
    <!-- 封装后的支付弹层=》使用效果 
     v-model:show="show"语法糖
     ===等价于
     :show="show" + @update:show
    -->
    <cp-pay-sheet
      v-model:show="show"
      :order-id="orderId"
      :actualPayment="payInfo.actualPayment"
      :onClose="onClose"
    />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
}
</style>
